package com.xumx.config;

import com.xumx.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configurers.userdetails.DaoAuthenticationConfigurer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * Created by Xumx on 2022/5/18 20:24
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private BCryptPasswordEncoder bcryptPasswordEncoder;


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制请求的授权规则
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/user/**").hasRole("vip1")
                .antMatchers("/order/**").hasRole("vip2");

        //没有权限默认会到登录页面，需要开启登录的页面
//        http.formLogin(); //使用的是SpringSecurity的登录页面
        http.formLogin().loginPage("/toLogin");  //自定义页面


        http.formLogin()
                .usernameParameter("username")
                .passwordParameter("password")
                // 哪个URL为登录页面
                .loginPage("/toLogin")
                // 当发现什么URL时执行登录逻辑
                .loginProcessingUrl("/login"); // 登陆表单提交请求

        http.csrf().disable();//关闭csrf功能
        //注销，开启注销功能
        http.logout();

        //http.rememberMe(); //官方默认的
        http.rememberMe().rememberMeParameter("remember");;
    }

    //定义认证规则
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //写死了 没有从数据库取值
        /*auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("xumx").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2")
                .and()
                .withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("vip1","vip2");*/

        //从数据库取值
        auth.userDetailsService(userServiceImpl).passwordEncoder(bcryptPasswordEncoder);
        DaoAuthenticationConfigurer<AuthenticationManagerBuilder, UserServiceImpl> service = auth.userDetailsService(userServiceImpl);

    }
}
